import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

# 数据定义
revenue = 570000  # 营业收入
cost_of_goods_sold = 460000  # 营业成本
net_profit = 13000  # 净利润
ebit = 14800  # 息税前利润
interest_expense = 1800  # 利息费用
total_liabilities = 329000  # 总负债
total_assets = 534000  # 总资产
current_assets = 154000  # 流动资产
current_liabilities = 118000  # 流动负债
inventory = 20000  # 存货
avg_receivables = 25000  # 应收账款
avg_inventory = 30000  # 平均存货
avg_fixed_assets = 80000  # 平均固定资产
avg_total_assets = 534000  # 平均总资产
avg_equity = 205000  # 平均净资产

# 财务指标计算
financial_ratios = {
    "资产负债率": total_liabilities / total_assets,
    "流动比率": current_assets / current_liabilities,
    "速动比率": (current_assets - inventory) / current_liabilities,
    "利息保障倍数": ebit / interest_expense,
    "应收账款周转率": revenue / avg_receivables,
    "存货周转率": cost_of_goods_sold / avg_inventory,
    "流动资产周转率": revenue / current_assets,
    "固定资产周转率": revenue / avg_fixed_assets,
    "总资产周转率": revenue / avg_total_assets,
    "毛利率": (revenue - cost_of_goods_sold) / revenue,
    "净利润率": net_profit / revenue,
    "净资产收益率": net_profit / avg_equity,
}

# 输出财务指标
print("Amazon 2023 财务指标结果：")
for key, value in financial_ratios.items():
    print(f"{key}: {value:.2%}")

# 更新英文名称的可视化代码
financial_ratios_en = {
    "Debt Ratio": total_liabilities / total_assets,
    "Current Ratio": current_assets / current_liabilities,
    "Quick Ratio": (current_assets - inventory) / current_liabilities,
    "Interest Coverage": ebit / interest_expense,
    "Receivables Turnover": revenue / avg_receivables,
    "Inventory Turnover": cost_of_goods_sold / avg_inventory,
    "Current Assets Turnover": revenue / current_assets,
    "Fixed Assets Turnover": revenue / avg_fixed_assets,
    "Total Assets Turnover": revenue / avg_total_assets,
    "Gross Margin": (revenue - cost_of_goods_sold) / revenue,
    "Net Profit Margin": net_profit / revenue,
    "Return on Equity": net_profit / avg_equity,
}

# 图表可视化
plt.figure(figsize=(12, 6))
plt.bar(financial_ratios_en.keys(), financial_ratios_en.values(), color="orange", alpha=0.7)
plt.title("Amazon 2023 Financial Ratios Analysis")
plt.ylabel("Ratio or Turnover")
plt.xticks(rotation=45)
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.tight_layout()
plt.show()

#财务报表分析
# 导入库
import matplotlib.pyplot as plt

# 数据定义
categories = ['Total Assets', 'Total Liabilities', 'Stockholders\' Equity']
values_2023 = [527854, 326979, 201875]  # 单位：百万美元

# 可视化 - 资产负债表构成饼图
fig, ax = plt.subplots()
ax.pie(values_2023, labels=categories, autopct='%1.1f%%', startangle=90, explode=(0.05, 0.05, 0.05))
ax.set_title('Amazon Balance Sheet Composition - 2023')

# 显示图表
plt.show()
# 数据定义
categories_income = ['Net Sales', 'Operating Income', 'Net Income']
values_income_2023 = [574785, 36852, 30425]  # 单位：百万美元

# 可视化 - 利润表结构柱状图
plt.figure(figsize=(8, 6))
plt.bar(categories_income, values_income_2023, color=['skyblue', 'orange', 'green'])
plt.title('Amazon Income Statement Overview - 2023')
plt.ylabel('Amount (in Million USD)')
plt.xlabel('Categories')
plt.grid(axis='y', linestyle='--', alpha=0.7)

# 显示图表
plt.show()
# 数据定义
categories_cashflow = ['Operating Activities', 'Investing Activities', 'Financing Activities']
values_cashflow_2023 = [84946, -49833, -15879]  # 单位：百万美元

# 可视化 - 现金流量表结构柱状图
plt.figure(figsize=(8, 6))
colors = ['green' if value > 0 else 'red' for value in values_cashflow_2023]
plt.bar(categories_cashflow, values_cashflow_2023, color=colors)
plt.title('Amazon Cash Flow Statement Overview - 2023')
plt.ylabel('Amount (in Million USD)')
plt.xlabel('Categories')
plt.grid(axis='y', linestyle='--', alpha=0.7)

# 显示图表
plt.show()

#股票预测分析
import pandas as pd
import matplotlib.pyplot as plt

# 文件路径
file_path = r"D:\作业\hd\期末\亚马逊年报\亚马逊股票市场数据\亚马逊股票市场数据2015-2024.csv"

# 读取数据，跳过第一行
stock_data = pd.read_csv(file_path, skiprows=1)

# 清理列名
stock_data.columns = stock_data.columns.str.strip().str.lower()

# 确定日期列名（假设为 'ticker'）
print("清理后的列名:", stock_data.columns)
print("前几行数据:\n", stock_data.head())

# 将 'ticker' 列转换为日期格式，并设置为索引
stock_data['ticker'] = pd.to_datetime(stock_data['ticker'])  # 解析日期列
stock_data.set_index('ticker', inplace=True)

# 绘制收盘价趋势图，使用 'amzn' 列表示收盘价
plt.figure(figsize=(12, 6))
plt.plot(stock_data.index, stock_data['amzn'], label='Closing Price', color='blue')
plt.title('Amazon Stock Price Trend (2015-2024)')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import pearsonr

# 1. 数据加载与修复
file_path = r"D:\作业\hd\期末\亚马逊年报\亚马逊股票市场数据\亚马逊股票市场数据2015-2024.csv"

# 设置正确的列名并清理数据
column_names = ['Date', 'Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume']
stock_data = pd.read_csv(file_path, skiprows=1, names=column_names)

# 清理数值列中的非数字字符
numeric_columns = ['Adj_Close', 'Close', 'High', 'Low', 'Open', 'Volume']
for col in numeric_columns:
    stock_data[col] = pd.to_numeric(stock_data[col], errors='coerce')  # 将无法转换的值设为 NaN

# 解析日期列
stock_data['Date'] = pd.to_datetime(stock_data['Date'], errors='coerce')
stock_data = stock_data.dropna(subset=['Date', 'Close'])  # 去除无效日期或无效数值

# 添加年份列
stock_data['Year'] = stock_data['Date'].dt.year

# 2. 按年份计算平均收盘价
avg_stock_price = stock_data.groupby('Year')['Close'].mean().reset_index()
avg_stock_price.columns = ['Year', 'Avg_Closing_Price']

# 3. 财务指标数据（2021-2023 年示例数据）
financial_data = pd.DataFrame({
    "Year": [2021, 2022, 2023],
    "Net_Income": [33364, -2722, 30425],  # 净利润
    "Gross_Profit_Margin": [0.17, 0.15, 0.193],  # 毛利率
    "Net_Profit_Margin": [0.071, -0.005, 0.0228],  # 净利润率
    "Return_on_Equity": [0.08, -0.01, 0.0634],  # 净资产收益率
})

# 合并股价数据与财务指标数据
combined_df = pd.merge(financial_data, avg_stock_price, on="Year", how="inner")

# 4. 相关性分析
metrics = ['Net_Income', 'Gross_Profit_Margin', 'Net_Profit_Margin', 'Return_on_Equity']
correlations = {}
for metric in metrics:
    corr, _ = pearsonr(combined_df['Avg_Closing_Price'], combined_df[metric])
    correlations[metric] = corr

print("相关性分析结果 (股价与财务指标):")
for k, v in correlations.items():
    print(f"{k}: {v:.2f}")

# 5. 数据可视化
# 股价与财务指标趋势图
plt.figure(figsize=(12, 6))
plt.plot(combined_df['Year'], combined_df['Avg_Closing_Price'], marker='o', label='Avg Closing Price')
plt.plot(combined_df['Year'], combined_df['Net_Income'], marker='o', label='Net Income')
plt.title("Amazon Stock Price and Financial Metrics (2021-2023)")
plt.xlabel("Year")
plt.ylabel("Values")
plt.legend()
plt.grid()
plt.show()

# 相关性热力图
plt.figure(figsize=(8, 6))
sns.heatmap(combined_df.corr(), annot=True, cmap="coolwarm", fmt=".2f")
plt.title("Correlation Matrix: Amazon Stock Price and Financial Metrics")
plt.show()

#模型构建
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_squared_error
import warnings

# 忽略警告
warnings.filterwarnings("ignore")

# 1. 加载数据
file_path = r"D:\作业\hd\期末\亚马逊年报\亚马逊股票市场数据\亚马逊股票市场数据2015-2024.csv"

# 读取数据
stock_data = pd.read_csv(file_path)

# 2. 数据预处理
# 修正列名
print("原始列名:", stock_data.columns)
stock_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Adj_Close', 'Volume']

# 日期转换，删除无效值
stock_data['Date'] = pd.to_datetime(stock_data['Date'], format='%Y-%m-%d', errors='coerce')
stock_data = stock_data.dropna(subset=['Date'])  # 删除无效日期

# 强制将 Close 列转换为数值，无法转换的设置为 NaN 并删除
stock_data['Close'] = pd.to_numeric(stock_data['Close'], errors='coerce')
stock_data = stock_data.dropna(subset=['Close'])

# 设置索引
stock_data.set_index('Date', inplace=True)

# 3. 数据可视化
plt.figure(figsize=(12, 6))
plt.plot(stock_data['Close'], label='Stock Closing Price')
plt.title("Amazon Stock Closing Price Trend (2015-2024)")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.grid()
plt.show()

# 4. ACF 和 PACF
plt.figure(figsize=(12, 6))
plot_acf(stock_data['Close'], lags=50, title="Autocorrelation of Stock Prices")
plot_pacf(stock_data['Close'], lags=50, title="Partial Autocorrelation of Stock Prices")
plt.show()

# 5. 拆分数据集
train_size = int(len(stock_data) * 0.8)
train, test = stock_data['Close'][:train_size], stock_data['Close'][train_size:]

# 6. 构建 ARIMA 模型
print("开始训练 ARIMA 模型...")
model = ARIMA(train, order=(5, 1, 2))
arima_result = model.fit()

# 7. 预测测试集
forecast = arima_result.forecast(steps=len(test))

# 8. 结果可视化
plt.figure(figsize=(12, 6))
plt.plot(train.index, train, label='Training Data')
plt.plot(test.index, test, label='Actual Prices', color='orange')
plt.plot(test.index, forecast, label='ARIMA Forecast', color='green')
plt.title("Amazon Stock Price Prediction using ARIMA")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.grid()
plt.show()

# 9. 模型评估
mse = mean_squared_error(test, forecast)
print(f"均方误差 (MSE): {mse:.2f}")

# 10. 预测未来30天股价
future_forecast = arima_result.forecast(steps=30)
future_dates = pd.date_range(stock_data.index[-1], periods=31, freq='B')[1:]

plt.figure(figsize=(12, 6))
plt.plot(stock_data['Close'], label="Historical Prices")
plt.plot(future_dates, future_forecast, label="Future Forecast", color='red')
plt.title("Amazon Stock Price Forecast for Next 30 Days")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.grid()
plt.show()

# 输出预测值
print("未来30天的预测股价:")
for date, price in zip(future_dates, future_forecast):
    print(f"{date.date()}: {price:.2f}")

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from pmdarima import auto_arima
from sklearn.metrics import mean_squared_error

# 1. 读取股票数据
file_path = r"D:\作业\hd\期末\亚马逊年报\亚马逊股票市场数据\亚马逊股票市场数据2015-2024.csv"
stock_data = pd.read_csv(file_path)
stock_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Adj_Close', 'Volume']
stock_data['Date'] = pd.to_datetime(stock_data['Date'], errors='coerce')  # 解析日期
stock_data = stock_data.dropna(subset=['Date', 'Close']).sort_values(by='Date')  # 删除NaN并按日期排序
stock_data.set_index('Date', inplace=True)

# 强制设定时间索引频率为工作日
stock_data = stock_data.asfreq('B').fillna(method='ffill')  # 填充缺失值

# 选取收盘价
stock_prices = stock_data['Close']

# 确保数据是纯浮点型
stock_prices = pd.to_numeric(stock_prices, errors='coerce').dropna()

# 2. 数据划分：训练集与测试集
train_data = stock_prices[:'2023']
test_data = stock_prices['2024':]

# 再次确保训练集和测试集是浮点型并无NaN
train_data = train_data.astype(float).dropna()
test_data = test_data.astype(float).dropna()

# 3. 自动选择ARIMA最佳参数
print("开始自动调参...")
model_auto = auto_arima(train_data, seasonal=False, trace=True,
                        error_action='ignore', suppress_warnings=True, stepwise=True)
print(f"最佳ARIMA参数: {model_auto.order}")

# 提取最佳参数
p, d, q = model_auto.order

# 4. 训练ARIMA模型
print("开始训练优化后的ARIMA模型...")
model = ARIMA(train_data, order=(p, d, q))
model_fit = model.fit()

# 5. 测试集预测
forecast = model_fit.forecast(steps=len(test_data))
mse = mean_squared_error(test_data, forecast)
print(f"均方误差 (MSE): {mse:.2f}")

# 6. 可视化结果：训练数据、实际数据和预测数据
plt.figure(figsize=(12, 6))
plt.plot(train_data, label='Training Data')
plt.plot(test_data, label='Actual Prices', color='orange')
plt.plot(test_data.index, forecast, label='ARIMA Forecast', color='green')
plt.title("Amazon Stock Price Prediction using Optimized ARIMA")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.show()

# 7. 未来30天预测
future_forecast = model_fit.forecast(steps=30)
future_dates = pd.date_range(start=stock_prices.index[-1], periods=30, freq='B')

# 可视化未来30天预测
plt.figure(figsize=(12, 6))
plt.plot(stock_prices, label='Historical Prices')
plt.plot(future_dates, future_forecast, label='Future Forecast', color='red')
plt.title("Amazon Stock Price Forecast for Next 30 Days")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.show()

# 输出未来30天预测结果
print("未来30天的预测股价：")
for date, price in zip(future_dates, future_forecast):
    print(f"{date.date()}: {price:.2f}")

#融合模型
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from pmdarima import auto_arima
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from sklearn.preprocessing import MinMaxScaler

# 财务数据（2023年）
financial_data = {
    "debt_to_asset_ratio": 61.6,        # 资产负债率
    "current_ratio": 131.0,            # 流动比率
    "quick_ratio": 114.0,              # 速动比率
    "interest_coverage": 822.2,        # 利息保障倍数
    "accounts_receivable_turnover": 228.0,  # 应收账款周转率
    "inventory_turnover": 153.3,       # 存货周转率
    "current_asset_turnover": 370.0,   # 流动资产周转率
    "total_asset": 527854,             # 总资产
    "total_liabilities": 326979,       # 总负债
    "current_asset": 154000,           # 流动资产
    "current_liabilities": 118000,     # 流动负债
    "inventory": 20000,                # 存货
    "ebit": 14800,                     # 息税前利润 (EBIT)
    "interest_expense": 1800,          # 利息费用
    "accounts_receivable": 25000,      # 应收账款
    "revenue": 574785,                 # 营业总收入
    "cost_of_goods_sold": 460000,      # 营业成本
    "fixed_asset": 80000,              # 固定资产
    "net_income": 13000,               # 净利润
    "net_asset": 205000,               # 净资产
    "fixed_asset_turnover": 713.5,     # 固定资产周转率
    "total_asset_turnover": 107.0,     # 总资产周转率
    "gross_margin": 19.3,              # 毛利率
    "operating_margin": 3.5,           # 营业利润率
    "net_margin": 2.3,                 # 净利润率
    "return_on_equity": 6.3            # 净资产收益率
}

# 1. 数据预处理
file_path = r"D:\作业\hd\期末\亚马逊年报\亚马逊股票市场数据\亚马逊股票市场数据2015-2024.csv"
stock_data = pd.read_csv(file_path)
stock_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Adj_Close', 'Volume']
stock_data['Date'] = pd.to_datetime(stock_data['Date'], errors='coerce')  # 解析日期
stock_data = stock_data.dropna(subset=['Date', 'Close']).sort_values(by='Date')  # 删除NaN并按日期排序
stock_data.set_index('Date', inplace=True)

# 强制设定时间索引频率为工作日
stock_data = stock_data.asfreq('B').fillna(method='ffill')  # 填充缺失值

# 选取收盘价
stock_prices = stock_data['Close']

# 将财务数据重复到时间序列长度
financial_series = pd.Series(financial_data)
financial_series.index = [f"financial_{col}" for col in financial_series.index]
financial_df = pd.DataFrame([financial_series] * len(stock_prices), index=stock_prices.index)

# 合并股票价格和财务数据
combined_data = pd.concat([stock_prices, financial_df], axis=1)

# 数据标准化
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(combined_data)

# 数据集划分
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size]
test_data = scaled_data[train_size:]

# 清理 stock_prices 数据
stock_prices = pd.to_numeric(stock_prices, errors='coerce').dropna()  # 转换为浮点型并移除 NaN
train_data_arima = stock_prices[:'2023']  # 选择训练集
test_data_arima = stock_prices['2024':]  # 选择测试集

# 确保训练数据为浮点型
train_data_arima = train_data_arima.astype(float)
test_data_arima = test_data_arima.astype(float)

# 验证数据是否正确
print("训练数据类型: ", train_data_arima.dtypes)
print("训练数据样本: ", train_data_arima.head())

# 自动选择ARIMA最佳参数
print("开始自动调参...")
arima_model_auto = auto_arima(train_data_arima, seasonal=False, trace=True,
                              error_action='ignore', suppress_warnings=True, stepwise=True)
print(f"最佳ARIMA参数: {arima_model_auto.order}")

# 提取最佳参数
p, d, q = arima_model_auto.order

# 训练ARIMA模型
print("开始训练ARIMA模型...")
arima_model = ARIMA(train_data_arima, order=(p, d, q))
arima_fit = arima_model.fit()

# 测试集预测
arima_forecast = arima_fit.forecast(steps=len(test_data_arima))
arima_mse = mean_squared_error(test_data_arima, arima_forecast)
print(f"ARIMA 均方误差 (MSE): {arima_mse:.2f}")

# 可视化ARIMA结果
plt.figure(figsize=(12, 6))
plt.plot(train_data_arima, label='Training Data')
plt.plot(test_data_arima, label='Actual Prices', color='orange')
plt.plot(test_data_arima.index, arima_forecast, label='ARIMA Forecast', color='green')
plt.title("Amazon Stock Price Prediction using ARIMA")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.show()

# 3. LSTM 模型
def create_lstm_dataset(data, time_steps=1):
    X, y = [], []
    for i in range(len(data) - time_steps):
        X.append(data[i:(i + time_steps), :])
        y.append(data[i + time_steps, 0])  # 收盘价是第0列
    return np.array(X), np.array(y)

time_steps = 30
X_train, y_train = create_lstm_dataset(train_data, time_steps)
X_test, y_test = create_lstm_dataset(test_data, time_steps)

# 定义 LSTM 模型
lstm_model = Sequential([
    LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])),
    LSTM(50, return_sequences=False),
    Dense(25, activation='relu'),
    Dense(1)
])
lstm_model.compile(optimizer='adam', loss='mean_squared_error')

# 训练 LSTM 模型
print("开始训练LSTM模型...")
lstm_model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1)

# LSTM 预测
lstm_predictions = lstm_model.predict(X_test)
lstm_predictions_rescaled = scaler.inverse_transform(
    np.hstack([lstm_predictions, np.zeros((lstm_predictions.shape[0], combined_data.shape[1] - 1))])
)[:, 0]

# 测试集实际值还原
y_test_rescaled = scaler.inverse_transform(
    np.hstack([y_test.reshape(-1, 1), np.zeros((y_test.shape[0], combined_data.shape[1] - 1))])
)[:, 0]

# LSTM 均方误差
lstm_mse = mean_squared_error(y_test_rescaled, lstm_predictions_rescaled)
print(f"LSTM 均方误差 (MSE): {lstm_mse:.2f}")

# 4. 加权融合
# 确保预测长度一致
if len(arima_forecast) > len(lstm_predictions_rescaled):
    arima_forecast = arima_forecast[:len(lstm_predictions_rescaled)]
elif len(arima_forecast) < len(lstm_predictions_rescaled):
    lstm_predictions_rescaled = lstm_predictions_rescaled[:len(arima_forecast)]

alpha = 0.5  # 权重系数
fusion_predictions = alpha * arima_forecast + (1 - alpha) * lstm_predictions_rescaled

# 可视化对比图
plt.figure(figsize=(12, 6))
plot_index = stock_prices.index[-len(lstm_predictions_rescaled):]  # 对齐索引
plt.plot(plot_index, y_test_rescaled[:len(plot_index)], label="Actual Prices", color='orange')
plt.plot(plot_index, arima_forecast[:len(plot_index)], label="ARIMA Predictions", color='green')
plt.plot(plot_index, lstm_predictions_rescaled[:len(plot_index)], label="LSTM Predictions", color='blue')
plt.plot(plot_index, fusion_predictions[:len(plot_index)], label="Fusion Predictions", color='red')
plt.title("Stock Price Prediction: ARIMA, LSTM, and Fusion")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.show()

# 未来30天预测
future_steps = 30
future_start_date = "2024-12-03"
future_end_date = "2025-01-13"

# 定义未来日期范围
future_dates = pd.date_range(start=future_start_date, end=future_end_date, freq='B')

# 准备 LSTM 输入数据（以最后 time_steps 长度的训练数据为基础）
future_input = scaled_data[-time_steps:]
future_input = future_input.reshape((1, time_steps, scaled_data.shape[1]))

future_forecast = []
for _ in range(future_steps):
    # 使用 LSTM 进行逐步预测
    future_price = lstm_model.predict(future_input)  # 预测未来价格，形状为 (1, 1)

    # 将 future_price 扩展为与 future_input 的特征维度一致
    feature_dim = future_input.shape[2]  # 获取 feature_dim（特征维度）
    future_price_expanded = np.zeros((1, 1, feature_dim))  # 创建形状匹配的数组
    future_price_expanded[:, :, 0] = future_price  # 将预测值填入第一列，其余列保持为 0

    # 拼接未来预测值到输入序列
    future_input = np.append(future_input[:, 1:, :], future_price_expanded, axis=1)

    # 记录预测结果
    future_forecast.append(future_price[0, 0])

# 将 LSTM 的未来预测结果反归一化
future_forecast_rescaled = scaler.inverse_transform(
    np.hstack([np.array(future_forecast).reshape(-1, 1), 
               np.zeros((len(future_forecast), combined_data.shape[1] - 1))])
)[:, 0]

# 可视化未来预测
plt.figure(figsize=(12, 6))
plt.plot(stock_prices, label='Historical Prices')
plt.plot(future_dates, future_forecast_rescaled, label='Future LSTM Forecast', color='red')
plt.title("Amazon Stock Price Forecast for Next 30 Days (2024-12-03 to 2025-01-13)")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.legend()
plt.show()

# 输出未来30天预测结果
print("未来30天的预测股价：")
for date, price in zip(future_dates, future_forecast_rescaled):
    print(f"{date.date()}: {price:.2f}")


